package com.stars.easyms.rest.handler;

import com.stars.easyms.base.constant.RestCodeConstants;
import com.stars.easyms.base.bean.EasyMsResponseEntity;
import com.stars.easyms.base.trace.EasyMsTraceSynchronizationManager;
import com.stars.easyms.feign.exception.BusinessFeignException;
import com.stars.easyms.rest.ResponseEntityHandler;
import com.stars.easyms.base.util.ExceptionUtil;
import com.stars.easyms.rest.exception.BusinessException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

/**
 * <p>className: EasyMsResponseEntityHandler</p>
 * <p>description: 默认的Rest响应处理类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-11 15:36
 */
public class EasyMsResponseEntityHandler<T> implements ResponseEntityHandler<T> {

    /**
     * 处理成功返回消息
     *
     * @param responseBody 返回参数
     * @return 返回消息
     */
    @NonNull
    @Override
    public EasyMsResponseEntity<T> getResponseEntity(@Nullable T responseBody) {
        EasyMsResponseEntity<T> responseEntity = new EasyMsResponseEntity<>();
        responseEntity.setRetCode(RestCodeConstants.DEFAULT_SUCC_CODE);
        responseEntity.setTraceId(EasyMsTraceSynchronizationManager.getTraceId());
        responseEntity.setBody(responseBody);
        return responseEntity;
    }

    /**
     * 处理异常类型的返回消息
     *
     * @param t 异常信息
     * @return 返回消息
     */
    @NonNull
    @Override
    public EasyMsResponseEntity<T> getResponseEntityWithException(@NonNull Throwable t) {
        EasyMsResponseEntity<T> responseEntity = new EasyMsResponseEntity<>();
        if (t instanceof BusinessException) {
            BusinessException businessException = (BusinessException) t;
            responseEntity.setRetCode(businessException.getRetCode());
            responseEntity.setRetMsg(businessException.getRetMsg());
            responseEntity.setErrorDesc(businessException.getErrorDesc());
        } else if (t instanceof BusinessFeignException) {
            BusinessFeignException businessFeignException = (BusinessFeignException) t;
            responseEntity.setRetCode(businessFeignException.getRetCode());
            responseEntity.setRetMsg(businessFeignException.getRetMsg());
            responseEntity.setErrorDesc(businessFeignException.getErrorDesc());
        } else {
            responseEntity.setRetCode(RestCodeConstants.DEFAULT_ERROR_CODE);
            responseEntity.setRetMsg(RestCodeConstants.DEFAULT_ERROR_MSG);
            responseEntity.setErrorDesc(ExceptionUtil.getExceptionDesc(t));
        }
        responseEntity.setTraceId(EasyMsTraceSynchronizationManager.getTraceId());
        return responseEntity;
    }

}